/**
 * InsertPost
 */
define('components/InsertPost/InsertPost', [
    'components/InsertPost/insertpost.css',
    'utils/fetchEnhancer',
    'utils/LinkedQueue',
    'utils/Time',
    'utils/helpers'], function(css, fetch, LinkedQueue, Time, helpers){

function InsertPost() {
    this.doc = document;

    this.jsRegex = /\[x_insert_post id="(\d+)"\]/g;
    this.queue = new LinkedQueue();
    this.container = null;
    this.html = '';
}
InsertPost.prototype = {
    constructor: InsertPost,
    getHtml: function() {
        return [
        '<a class="insert-post-wrapper" href="{link}">',
            '<span class="insert-post-bg" style="background-image:url({thumb})"></span>',
            '<span class="insert-post-img" style="background-image:url({thumb})"></span>',
            '<span class="insert-post-content">',
                '<span class="insert-post-content-title">{title}</span>',
                '<span class="insert-post-content-meta">{brief}</span>',
                '<span style="text-align: right" class="insert-post-content-meta">{time}</span>',
            '</span>',
        '</a>'].join('');
    },
    findAllPosts: function() {
        let parts = null;

        while( null !== (parts = this.jsRegex.exec(this.html)) ) {
            this.queue.add(parts[1]);
        }

        if(this.queue.size > 0) {
            this.fetchPost();
        }
    },
    replaceInsert: function(data) {
        var template = this.getHtml();
        template = template.replace('{link}', helpers.U('posts', {id: data.id}));
        template = template.replace('{thumb}', data.thumb);
        template = template.replace('{thumb}', data.thumb);
        template = template.replace('{title}', data.title);
        template = template.replace('{brief}', data.brief);
        template = template.replace('{time}', Time.format('y-m-d', data.post_time * 1000));

        this.html = this.html.replace('[x_insert_post id="'+ data.id +'"]', template);
    },
    fetchPost: function() {
        let _self = this;
        let id = this.queue.take();

        if(!id) {
            this.container.innerHTML = this.html;
            return;
        }

        fetch('/api/post/get?id=' + id).then((rs) => {
            if(0 === rs.status) {
                _self.replaceInsert(rs.data.data);
                _self.fetchPost();
            }
        });
    },
    process: function(container) {
        this.container = container;
        this.html = this.container.innerHTML;

        this.findAllPosts();
    }
};

return InsertPost;

});
